﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PASNew.U.Controls
{
    public partial class AdminUC : System.Web.UI.UserControl
    {
        int userlevel;
        int numclients;

        private void ClearControls()
        {
            foreach (Control c in Page.Controls)
            {
                foreach (Control ctrl in c.Controls)
                {
                    if (ctrl is TextBox)
                    {
                        ((TextBox)ctrl).Text = string.Empty;
                    }
                }
            }
        }

        string makeCamel(string original)
        {
            if (string.IsNullOrEmpty(original)) return string.Empty;
            // convert to char array of the string    
            char[] letters = original.ToCharArray();
            // upper case the first char    
            letters[0] = char.ToUpper(letters[0]);
            // return the array made of the new char array    
            return new string(letters);
        } //used to change text to the correct format

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["DeletedUser"] != null)
            {
                lblSuccess.Visible = true;
                lblSuccess.Text = "User was successfully deleted";
            }

            if (Session["UserIdentity"] != null)
            {
                if (IsPostBack == false)
                {
                    UserDetailsDto user = (UserDetailsDto)Session["UserIdentity"];

                    CompIDdto userCompany = (CompIDdto)Session["CompanyIdentitifier"];

                    using (PASDataDataContext data = new PASDataDataContext())
                    {
                        var Alevel = (from a in data.UserDetails
                                      where a.UserId == user.UserID
                                      select a).FirstOrDefault();

                        userlevel = int.Parse(Alevel.UserLevel.ToString());

                        if (Alevel != null)
                        {
                            if (Alevel.UserLevel == 4)
                            {
                                Response.Redirect("Home.aspx");
                            }
                            else
                            {
                                if (Alevel.UserLevel == 2)
                                {
                                    txtBoxUserALevel.Visible = true;
                                    lblALevel.Visible = true;

                                    var PowerUser = from us in data.UserDetails
                                                    where us.UserLevel >= 3
                                                    select new ListItem
                                                    {
                                                        Text = us.UserName,
                                                        Value = us.UserId.ToString(),
                                                    };
                                    foreach (ListItem l in PowerUser)
                                    {
                                        DDUsers.Items.Add(l);
                                    }
                                }
                                else
                                {
                                    var ManageUsers = from u in data.UserDetails
                                                      where u.UserLevel == 4
                                                      select new ListItem
                                                      {
                                                          Text = u.UserName,
                                                          Value = u.UserId.ToString(),
                                                      };

                                    foreach (ListItem l in ManageUsers)
                                    {
                                        DDUsers.Items.Add(l);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                Response.Redirect("Home.aspx");
            }
        }

        protected void btnNewUser_Click(object sender, EventArgs e)
        {
            ClearControls();
            Response.Redirect("Admin.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (PASDataDataContext data = new PASDataDataContext())
            {
                CompIDdto CompIdent = (CompIDdto)Session["CompIdentity"];
                UserDetailsDto user = (UserDetailsDto)Session["UserIdentity"];

                var Alevel = (from a in data.UserDetails
                              where a.UserId == user.UserID
                              select a).FirstOrDefault();

                var check = (from c in data.UserDetails
                             where c.UserEmail == txtBoxUserEmail.Text.ToString()
                             select c).FirstOrDefault();

                if (check != null) //if true update user details
                {
                    check.UserName = makeCamel(txtBoxUserName.Text);
                    check.UserEmail = txtBoxUserEmail.Text.ToString();
                    check.UserPassword = txtBoxPassword.Text.ToString();

                    if (Alevel.UserLevel == 2)
                    {
                        check.UserLevel = int.Parse(txtBoxUserALevel.Text.ToString());
                    }
                    else
                    {
                        check.UserLevel = 4;
                    }
                    lblSuccess.Text = "User successfully updated";
                    lblSuccess.Visible = true;

                    data.SubmitChanges();
                }
                else
                {
                    UserDetail Save = new UserDetail();

                    Save.UserName = makeCamel(txtBoxUserName.Text);
                    Save.UserEmail = txtBoxUserEmail.Text.ToString();
                    Save.UserPassword = txtBoxPassword.Text.ToString();

                    if (userlevel == 2)
                    {
                        Save.UserLevel = int.Parse(txtBoxUserALevel.Text.ToString());
                    }
                    else
                    {
                        Save.UserLevel = 4;
                    }

                    data.UserDetails.InsertOnSubmit(Save);
                    data.SubmitChanges();

                    var loadsave = (from c in data.UserDetails
                                    where c.UserEmail == txtBoxUserEmail.Text.ToString()
                                    select c).FirstOrDefault();

                    CompanyUserRelation NewRelationship = new CompanyUserRelation();

                    NewRelationship.UserId = int.Parse(loadsave.UserId.ToString());
                    NewRelationship.CompanyId = CompIdent.CompID;

                    data.CompanyUserRelations.InsertOnSubmit(NewRelationship);
                    data.SubmitChanges();

                    lblSuccess.Text = "User successfully saved";
                    lblSuccess.Visible = true;
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int identity;

            using (PASDataDataContext data = new PASDataDataContext())
            {
                var x = (from c in data.UserDetails
                         where c.UserEmail == txtBoxUserEmail.Text.ToString()
                         select c).FirstOrDefault();

                identity = x.UserId;

                data.UserDetails.DeleteOnSubmit(x);

                var z = (from y in data.CompanyUserRelations
                         where y.UserId == identity
                         select y).FirstOrDefault();

                data.CompanyUserRelations.DeleteOnSubmit(z);
                data.SubmitChanges();
            }

            lblSuccess.Text = "User successfully deleted";
            lblSuccess.Visible = true;
        }

        protected void DDUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnLoadClient.Visible = true;
            pClients.Visible = true;
            cbClients.Visible = true;
            lblNumClients.Visible = true;
            btnMoveClient.Visible = true;
            DDMove.Visible = false;
            lblSuccess.Visible = false;
            cbClients.Items.Clear();
            numclients = 0;
            if(DDUsers.SelectedValue != "-1")
            {
                using (PASDataDataContext data = new PASDataDataContext())
                {
                    var Details = (from u in data.UserDetails
                                   where u.UserId.ToString() == DDUsers.SelectedValue
                                   select u).FirstOrDefault();

                    txtBoxUserName.Text = Details.UserName;
                    txtBoxUserEmail.Text = Details.UserEmail;
                    txtBoxPassword.Text = Details.UserPassword;
                    txtBoxUserALevel.Text = Details.UserLevel.ToString();

                    if (userlevel == 2)
                    {
                        lblALevel.Visible = true;
                        txtBoxUserALevel.Visible = true;
                        txtBoxUserALevel.Text = Details.UserLevel.ToString();
                    }

                    var cDetails = from c in data.ClientUserRelations
                                   where c.UserId == Details.UserId
                                   select new ListItem
                                   {
                                       Value = c.ClientId.ToString(),
                                   };
                    foreach (ListItem l in cDetails)
                    {
                        var UsersCleints = (from d in data.ClientDetails
                                            where d.ClientId == int.Parse(l.Value.ToString())
                                            select d).FirstOrDefault();

                        cbClients.Items.Add(UsersCleints.CompanyName.ToString());

                        numclients++;
                    }                   
                }                
            }
            lblNumClients.Text = "Number of clients: " + numclients.ToString();
        }

        protected void DDMove_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnMoveClient.Visible = true;
            DDMove.Visible = false;
        }

        protected void btnLoadClient_Click(object sender, EventArgs e)
        {
              for (int i = 0; i < cbClients.Items.Count; i++)
            {
                if (cbClients.Items[i].Selected)
                {
                    if (i == 0)
                    {
                        AdminDto AdminComp = new AdminDto
                        {
                            AdminCompName = cbClients.Items[i].Value,
                        };

                        Session["AdminCompanyName"] = AdminComp;
                        Response.Redirect("AdminClients.aspx");

                    }                    
                }  
            }

        }

        protected void btnMoveClient_Click(object sender, EventArgs e)
        {
            btnMoveClient.Visible = false;
            DDMove.Visible = true;
        }
    }
}